package com.greenphosphor.glasshouse;

import java.util.*;
import java.util.logging.*;

public class RegionControl {

  public int[] primGraphIds;
  public String region;
  private int lastFreePrim = 0;
  private int nextGraphId = 1;
  public static final int MAX_GRAPHID = 500000;
  private Logger log;

  public RegionControl ( String inRegion, int inPrimCount,
                         Logger inLog ) {
    region = inRegion;
    primGraphIds = new int[inPrimCount];
    for ( int i = 0; i < inPrimCount; i++ )
      primGraphIds[i] = 0;
    log = inLog;
  }

  public String getNextFreePrim ( int graphId, String nodeIdStr,
                                  HashMap<String, Integer> nodeMap ) {
    int numChecked = 0;
    while ( primGraphIds[lastFreePrim] != 0 && numChecked <= primGraphIds.length ) {
      lastFreePrim++;
      if ( lastFreePrim >= primGraphIds.length )
        lastFreePrim = 0;
      numChecked++;
    }
    if ( numChecked >= primGraphIds.length )
      return "full";
    primGraphIds[lastFreePrim] = graphId;
    nodeMap.put(nodeIdStr, new Integer(lastFreePrim + 1));
    //log.info("rc returns " + String.valueOf(lastFreePrim + 1) + ", checked " + numChecked);
    return String.valueOf(lastFreePrim + 1);
  }

  public void freePrims ( int graphId ) {
    int c = 0;
    for ( int i = 0; i < primGraphIds.length; i++ ) {
      if ( primGraphIds[i] == graphId ) {
        c++;
        primGraphIds[i] = 0;
      }
    }
    log.info("rc freed up " + c);
  }

  public LinkedList getPrimList ( int graphId ) {
    LinkedList ll = new LinkedList();
    for ( int i = 0; i < primGraphIds.length; i++ ) {
      if ( primGraphIds[i] == graphId )
        ll.add(new Integer(i));
    }
    return ll;
  }

  public void freePrims ( LinkedList ll, int layer ) {
    ListIterator li = ll.listIterator();
    while ( li.hasNext() ) {
      Integer iObj = (Integer)li.next();
      primGraphIds[iObj.intValue()] = 0;
    }
  }

  public synchronized int getNextGraphId () {
    int id = nextGraphId;
    nextGraphId++;
    if ( nextGraphId > MAX_GRAPHID )
      nextGraphId = 1;
    return id;
  }

  public void freePrim ( int id ) {
    primGraphIds[id] = 0;
  }
}

